<?php
namespace app\admin\service;

class User extends BaseService
{
    /**
     * 登录接口
     * @param $username
     * @param $password
     * @return bool|string
     */
    function login($username,$password)
    {
        $userLogic = new \app\admin\logic\User();
        $admin = $userLogic->findAdminByName($username);

        if(empty($admin)){
            return '管理员不存在';
        }

        if(empty($admin->group_id)){
            return '登录被限制';
        }

        if($this->password($password,$admin->salt,$admin->check_type) == $admin->pwd){
            session('userdata',$admin);
            return true;
        }

        return '密码错误';

    }

    /**
     * 注册接口
     * @param $username
     * @param $password
     * @return bool|string
     */
    function register($username,$password,$group_id=0)
    {
        $admin = model('User','Logic')->findAdminByName($username);

        if(!empty($admin)){
            return '管理员已经存在';
        }
        $data['user_name'] = $username;
        $data['salt'] = mb_substr(uuid(),0,6);
        $data['check_type'] = rand(1,6);
        $data['pwd'] = $this->password($password,$data['salt'],$data['check_type']);
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['group_id'] = $group_id;
        $data['nickname'] = $username;

        $re = model('User','Logic')->createAdmin($data);
        if($re){
            return true;
        }
        return '添加管理员失败';
    }

    /***
     * 检测 用户密码是否正确
     * @param $data
     * @param $password
     * @return bool
     */
    public function password($password,$salt,$type=1){
        switch ($type)
        {
            case 1:
                return md5($password.config('app.auth_key_1').$salt);
            case 2:
                return md5($password.config('app.auth_key_2').$salt);
            case 3:
                return sha1($password.$salt.config('app.auth_key_1'));
            case 4:
                return sha1($password.$salt.config('app.auth_key_2'));
            case 5:
                return sha1(md5(config('app.auth_key_1').$password.$salt));
            case 6:
                return sha1(md5(config('app.auth_key_2').$password.$salt));
            default:
                return false;
        }
    }
}